package com.pkutech.carcasher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.pkutech.carcasher.R;
import com.pkutech.carcasher.bean.TestBean;
import com.pkutech.carcasher.view.PopMenuAction;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * "车位搜索"模块
 * Created by cyy on 2016/6/11.
 */
public class ParkingQueryActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.bmapView)
    MapView mMapView;
    BaiduMap mBaiduMap;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    BitmapDescriptor bdA = BitmapDescriptorFactory.fromResource(R.drawable.icon_marka);
    Map<Marker, TestBean> parkingMarkerMap = new HashMap<Marker, TestBean>();
    //底部弹出菜单布局
    View orderActionView;
    //底部弹出菜单
    PopMenuAction orderAction;
    TextView parkingNameTxt, leftParkingTxt;
    TestBean currentTestBean;
    boolean isFirstLoc = true; // 是否首次定位

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parking_query);
        ButterKnife.bind(this);
        initToolbar(toolbar);
        // 地图初始化
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
        initOverlay();
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            public boolean onMarkerClick(final Marker marker) {
                currentTestBean = parkingMarkerMap.get(marker);
                parkingNameTxt.setText(currentTestBean.getParkingName());
                leftParkingTxt.setText("剩余" + currentTestBean.getLeftParking() + "个车位");
                showMoreAction();
                return true;
            }
        });

        initBottomPopupMenu();
    }

    @OnClick(R.id.searchParkEditText)
    public void toSearchParking(View view) {
        Intent intent = new Intent(this, ParkingSearchActivity.class);
        startActivity(intent);
    }

    public void showParkingDetail(View view) {
        Intent intent = new Intent(this, ParkingDetailActivity.class);
        startActivity(intent);
    }

    private void initBottomPopupMenu() {
        orderActionView = getLayoutInflater().inflate(R.layout.parking_query_action_view, null, false);
        LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.pop_order_action_height));
        orderActionView.setLayoutParams(ll);
        parkingNameTxt = (TextView) orderActionView.findViewById(R.id.parkingNameTxt);
        leftParkingTxt = (TextView) orderActionView.findViewById(R.id.leftParkingTxt);
    }

    /**
     * 打开底部菜单
     */
    private void showMoreAction() {
        ViewGroup vg = (ViewGroup) orderActionView.getParent();
        if (null != vg) {
            vg.removeAllViews();
        }

        if (null != orderAction) {
            orderAction.dismiss();
            orderAction = null;
        } else {
            orderAction = PopMenuAction.createBuilder(this, getSupportFragmentManager())
                    .setContentView(orderActionView)
                    .setFrom(PopMenuAction.FROM_BOTTOM)
                    .setCancelableOnTouchOutside(true).show();
            orderAction.setActionSheetListener(new PopMenuAction.ActionSheetListener() {
                @Override
                public void onDismiss(PopMenuAction actionSheet, boolean isCancel) {
                    orderAction = null;
                }

                @Override
                public void onOtherButtonClick(PopMenuAction actionSheet, int index) {

                }
            });
        }
    }

    public void initOverlay() {
        // add marker overlay
        LatLng llA = new LatLng(31.498044, 120.380037);
        MarkerOptions ooA = new MarkerOptions().position(llA).icon(bdA)
                .zIndex(9).draggable(true);
        // 掉下动画
        ooA.animateType(MarkerOptions.MarkerAnimateType.drop);
        TestBean tb = new TestBean();
        tb.setParkingName("xxxxxxxxxxxxxx停车场");
        tb.setLeftParking(26);
        parkingMarkerMap.put((Marker) (mBaiduMap.addOverlay(ooA)), tb);
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(16.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    @Override
    protected void onPause() {
        // MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        // MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
        mMapView.onResume();
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        // MapView的生命周期与Activity同步，当activity销毁时需调用MapView.destroy()
        mMapView.onDestroy();
        mMapView = null;
        // 回收 bitmap 资源
        bdA.recycle();
        super.onDestroy();
    }

}